<!doctype html>
<html lang="zh-Hans">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="hugo-theme" content="Axiom 0.7.1">



  <link rel="icon" type="image/png" sizes="32x32" href="/blog/">
  <link rel="icon" type="image/x-icon" href="/blog/">
  <link rel="apple-touch-icon" href="/blog/">
  <link rel="canonical" href="https://Mia-zhao.gitee.io/blog/implement-an-event-emitter/">
<link rel="preload" as="style" href="/blog/bundle.css?v=1603792187" media="all">
<link rel="stylesheet" href="/blog/bundle.css?v=1603792187" media="all">
<style>.cdata pre{color:#edf2f7;background-color:#2d3748}.cdata :not(pre)>code{color:#805ad5;background-color:#f7fafc}.chroma .err{color:#fed7d7;background-color:#9b2c2c}.chroma .hl{background-color:#4a5568}.chroma .ln{color:#a0aec0}.chroma .k,.chroma .kc,.chroma .kd,.chroma .kn,.chroma .kp,.chroma .kr{color:#63b3ed}.chroma .kt{color:#b794f4}.chroma .na{color:#f6e05e}.chroma .nb{color:#f6ad55}.chroma .nc{color:#fc8181}.chroma .no{color:#68d391}.chroma .nd{color:#fc8181}.chroma .ne{color:#fc8181}.chroma .nf{color:#f6ad55}.chroma .nt{color:#fc8181}.chroma .l{color:#b794f4}.chroma .dl,.chroma .ld,.chroma .s,.chroma .s2,.chroma .sa,.chroma .sb,.chroma .sc,.chroma .sd{color:#68d391}.chroma .se{color:#a0aec0}.chroma .s1,.chroma .sh,.chroma .si,.chroma .sr,.chroma .ss,.chroma .sx{color:#68d391}.chroma .il,.chroma .m,.chroma .mb,.chroma .mf,.chroma .mh,.chroma .mi,.chroma .mo{color:#b794f4}.chroma .o,.chroma .ow{color:#90cdf4}.chroma .p{color:#cbd5e0}.chroma .c,.chroma .c1,.chroma .ch,.chroma .cm,.chroma .cp,.chroma .cpf,.chroma .cs{color:#a0aec0}.chroma .ge{font-style:italic}.chroma .gs{font-weight:700}</style>



<title>Implement an Event Emitter : Mia&#39;s Blog Posts</title>

<meta property="og:title" content="Implement an Event Emitter">
<meta property="og:site_name" content="Mia&#39;s Blog Posts">
<meta property="og:url" content="https://Mia-zhao.gitee.io/blog/implement-an-event-emitter/">
<link rel="image_src" href="https://Mia-zhao.gitee.io/blog/">
<meta property="og:image" content="https://Mia-zhao.gitee.io/blog/">
<meta property="og:image:width" content="">
<meta property="og:image:height" content="">
<meta property="og:type" content="article">
<meta property="og:locale" content="zh_Hans">
<meta property="og:description" content="I was asked to implement an event emitter class in one of the front-end job interviews. A few APIs were given in the interview question and an emitter class should fulfill these APIs. class Emitter {// TODO}const emitter = new Emitter()const dispose = emitter.on(&#39;event1&#39;, (data) =&amp;gt; {console.log(data)})emitter.fire(&#39;event1&#39;, { a: &#39;text&#39; })dispose()Consider the code above, it&#39;s intuitive that the Emitter class should have methods on and fire which registers an event listener and fires a specific event respectively.">
<meta name="description" content="I was asked to implement an event emitter class in one of the front-end job interviews. A few APIs were given in the interview question and an emitter class should fulfill these APIs. class Emitter {// TODO}const emitter = new Emitter()const dispose = emitter.on(&#39;event1&#39;, (data) =&amp;gt; {console.log(data)})emitter.fire(&#39;event1&#39;, { a: &#39;text&#39; })dispose()Consider the code above, it&#39;s intuitive that the Emitter class should have methods on and fire which registers an event listener and fires a specific event respectively.">
<meta property="og:updated_time" content="2020-10-26T08:00:00Z">
<meta property="fb:app_id" content="">
<meta name="author" content="Mia Zhao">
<meta property="article:author" content="https://mia-zhao.gitee.io/">
<meta property="article:published_time" content="2020-10-26T08:00:00Z">
<meta property="article:modified_time" content="2020-10-26T08:00:00Z">
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "Implement an Event Emitter",
  "alternativeHeadline": "I was asked to implement an event emitter class in one of the front-end job interviews. A few APIs were given in the interview question and an emitter class should fulfill these APIs. class Emitter {\r// TODO\r}\rconst emitter = new Emitter()\rconst dispose = emitter.on('event1', (data) =\u0026gt; {\rconsole.log(data)\r})\remitter.fire('event1', { a: 'text' })\rdispose()\rConsider the code above, it's intuitive that the Emitter class should have methods on and fire which registers an event listener and fires a specific event respectively.",
  "url": "https://Mia-zhao.gitee.io/blog/implement-an-event-emitter/",
  "image": "https://Mia-zhao.gitee.io/blog/",
  "mainEntityOfPage": {
    "@type": "WebPage",
    "@id": "https://Mia-zhao.gitee.io/blog/implement-an-event-emitter/"
  },
  "description": "I was asked to implement an event emitter class in one of the front-end job interviews. A few APIs were given in the interview question and an emitter class should fulfill these APIs. class Emitter {\r// TODO\r}\rconst emitter = new Emitter()\rconst dispose = emitter.on('event1', (data) =\u0026gt; {\rconsole.log(data)\r})\remitter.fire('event1', { a: 'text' })\rdispose()\rConsider the code above, it's intuitive that the Emitter class should have methods on and fire which registers an event listener and fires a specific event respectively.",
  "author": {
    "@type": "Person",
    "name": "Mia Zhao"
  },
  "publisher": {
    "@type": "Organization",
    "name": "Mia's Blog Posts",
    "logo": {
      "@type": "ImageObject",
      "url": "https://Mia-zhao.gitee.io/blog/"
    }
  },
  "datePublished": "2020-10-26T08:00:00Z",
  "dateModified": "2020-10-26T08:00:00Z",
  "articleBody": "\u003cp\u003eI was asked to implement an event emitter class in one of the front-end job interviews. A few APIs were given in the interview question and an emitter class should fulfill these APIs.\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eclass Emitter {\r\n  // TODO\r\n}\r\n\r\nconst emitter = new Emitter()\r\nconst dispose = emitter.on('event1', (data) =\u0026gt; {\r\n  console.log(data)\r\n})\r\nemitter.fire('event1', { a: 'text' })\r\ndispose()\r\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eConsider the code above, it's intuitive that the \u003ccode\u003eEmitter\u003c/code\u003e class should have methods \u003ccode\u003eon\u003c/code\u003e and \u003ccode\u003efire\u003c/code\u003e which registers an event listener and fires a specific event respectively. At a closer look, the \u003ccode\u003eon\u003c/code\u003e method should return a function which unregisters the event listener.\n\u003cimg src=\"/blog/images/emitter_class.png\" alt=\"Image of Emitter Class\"\u003e\u003c/p\u003e\n\u003cp\u003eRecall a similar function call \u003ccode\u003edocument.addEventListener('click', () =\u0026gt; {})\u003c/code\u003e, one event could have multiple listeners.\u003c/p\u003e\n\u003cp\u003eWe can start with the boilerplate for the \u003ccode\u003eEmitter\u003c/code\u003e class like this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eclass Emitter {\r\n  constructor() {\r\n    listeners = {}\r\n  }\r\n\r\n  on(event, fn) {}\r\n\r\n  fire(event, data) {}\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eWith the \u003ccode\u003eon\u003c/code\u003e method, an event listener should be registerd:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eon(event, fn) {\r\n  this.listeners[event] = this.listeners[event] || []\r\n  this.listeners[event].push(fn)\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eThe \u003ccode\u003eon\u003c/code\u003e method should also return a function to unregister the listener:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eon(event, fn) {\r\n  this.listeners[event] = this.listeners[event] || []\r\n  this.listeners[event].push(fn)\r\n  return function() {\r\n    const index = this.listeners.indexOf(fn)\r\n    this.listeners.splice(index, 1)\r\n  }\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eThe \u003ccode\u003eemit\u003c/code\u003e method should call each listener of the event:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003efire(event, data) {\r\n  this.listeners[event].forEach((fn) =\u0026gt; {\r\n    fn.call(this, data)\r\n  })\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003ePutting together, we have \u003ccode\u003eEmitter\u003c/code\u003e class\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003eclass Emitter {\r\n  constructor() {\r\n    listeners = {}\r\n  }\r\n\r\n  on(event, fn) {\r\n    this.listeners[event] = this.listeners[event] || []\r\n    this.listeners[event].push(fn)\r\n    return function() {\r\n      const index = this.listeners.indexOf(fn)\r\n      this.listeners.splice(index, 1)\r\n    }\r\n  }\r\n\r\n  fire(event, data) {\r\n    this.listeners[event].forEach((fn) =\u0026gt; {\r\n      fn.call(this, data)\r\n    })\r\n  }\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eThere are a few considerations:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003ePassing arguments and \u003ccode\u003ethis\u003c/code\u003e to listeners: keep in mind that when a listener function is called, \u003ccode\u003ethis\u003c/code\u003e should be referencing \u003ccode\u003eEmitter\u003c/code\u003e instance\u003c/li\u003e\n\u003cli\u003eAsynchronous vs synchronous: \u003ccode\u003eEmitter\u003c/code\u003e calls all listeners synchronously in the order they were registered\u003c/li\u003e\n\u003c/ul\u003e"
}
</script>

<link rel="preload" as="script" href="/blog/bundle.js?v=1603792187">


</head>
<body>

  <header id="nav" class="header">
  <div class="ax-l-i max-w-6xl">
    <div class="ax-logo">
      <a class="block" href="/blog/" title="Mia&#39;s Blog Posts"><span class="font-semibold text-raven-900">Mia's Blog Posts</span></a>
    </div>
    <div class="ax-user">
      <a class="p-2 w-8 h-8 block text-raven-500 hover:text-gray-800 focus:text-gray-800 focus:outline-none" target="_blank" rel="noopener nofollow" href="https://www.google.com/search?q=site:https://Mia-zhao.gitee.io/blog/" title="Search">
        <svg class="fill-current" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M2.67 12.804c0-5.6 4.544-10.134 10.133-10.134s10.134 4.544 10.134 10.134-4.544 10.133-10.134 10.133S2.67 18.393 2.67 12.804zm28.943 16.923l-8.868-8.868c4.287-5.3 3.68-13.012-1.378-17.57S8.564-1.066 3.75 3.75s-5.017 12.558-.46 17.618 12.28 5.665 17.57 1.378l8.868 8.868a1.33 1.33 0 0 0 2.231-.597c.123-.46-.008-.952-.345-1.29h0z"/></svg>

      </a>
      <a class="p-2 block text-base leading-none text-raven-500 hover:text-gray-800 focus:text-gray-800 focus:outline-none" href="/blog/posts/">
        Posts
      </a>
    </div>
  </div>

  
</header>

  <main>
<div class="default-single">
  <div class="ax-title ax-l-o">
    <div class="ax-l-i max-w-680">
      <h1 class="post-title font-content-title font-normal leading-tight tracking-default text-40">Implement an Event Emitter</h1>

      <div class="ax-meta flex items-center mt-5">
        <div class="flex-grow min-w-0">
          <div class="flex items-center">
  <div class="flex-shrink-0">
    <img
    class="w-12 h-12 sm:w-14 sm:h-14 object-cover p-3px rounded-full border border-blue-300"
    src="/blog/images/author/default.webp"
    alt="Mia Zhao">
  </div>
  <div class="flex-shrink-0 ml-2 leading-tight font-content-sans">
    <a class="block text-sm text-raven-800 hover:text-raven-900 hover:underline focus:underline" target="_blank" rel="noopener nofollow" title="Mia Zhao" href="https://mia-zhao.gitee.io/">Mia Zhao</a>
    <time class="text-sm text-raven-500" datetime="2020-10-26T08:00:00Z">Oct 26, 2020 4:00PM</time>
  </div>
</div>

        </div>
        <div>
          <div class="flex items-center">
  <a class="flex-shrink-0 block text-raven-800 hover:text-raven-900" target="_blank" rel="noopener nofollow" title="Share on Twitter" href="https://twitter.com/intent/tweet?text=Implement%20an%20Event%20Emitter%20by%20%40%25%21s%28%3cnil%3e%29%20https%3a%2f%2fMia-zhao.gitee.io%2fblog%2fimplement-an-event-emitter%2f"><svg class="w-6 h-6 fill-current" viewBox="0 0 32 32" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M32 6.078c-1.2.522-2.458.868-3.78 1.036 1.36-.812 2.398-2.088 2.886-3.626a13.11 13.11 0 0 1-4.16 1.588C25.742 3.794 24.026 3 22.154 3a6.56 6.56 0 0 0-6.556 6.562c0 .52.044 1.02.152 1.496-5.454-.266-10.28-2.88-13.522-6.862-.566.982-.898 2.106-.898 3.316a6.57 6.57 0 0 0 2.914 5.452 6.48 6.48 0 0 1-2.964-.808v.072c0 3.188 2.274 5.836 5.256 6.446-.534.146-1.116.216-1.72.216-.42 0-.844-.024-1.242-.112.85 2.598 3.262 4.508 6.13 4.57a13.18 13.18 0 0 1-8.134 2.798c-.538 0-1.054-.024-1.57-.1C2.906 27.93 6.35 29 10.064 29c12.072 0 18.672-10 18.672-18.668 0-.3-.01-.57-.024-.848C30.014 8.56 31.108 7.406 32 6.078z"/></svg>
</a>
  <a class="ml-3 flex-shrink-0 block text-raven-800 hover:text-raven-900" target="_blank" rel="noopener nofollow" title="Share on Facebook" href="https://www.facebook.com/dialog/share?app_id=&display=page&href=https%3a%2f%2fMia-zhao.gitee.io%2fblog%2fimplement-an-event-emitter%2f"><svg class="w-6 h-6 fill-current" viewBox="-7 -3.5 39 39" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M30.234 0H1.765C.8.001 0 .79 0 1.766v28.47C.001 31.2.79 32 1.766 32h15.328V19.625h-4.156V14.78h4.156v-3.564c0-4.134 2.523-6.384 6.21-6.384 1.766 0 3.284.13 3.726.2v4.32h-2.543c-2.006 0-2.394.953-2.394 2.352v3.085h4.797l-.625 4.844h-4.172V32h8.14C31.21 32 32 31.2 32 30.234V1.765C32 .8 31.21 0 30.234 0z"/></svg>
</a>
</div>

        </div>
      </div>
    </div>
  </div><div class="ax-content ax-l-o">
    <div class="ax-l-i max-w-680">
      <article class="cdata">
<p>I was asked to implement an event emitter class in one of the front-end job interviews. A few APIs were given in the interview question and an emitter class should fulfill these APIs.</p>
<pre><code>class Emitter {
  // TODO
}

const emitter = new Emitter()
const dispose = emitter.on('event1', (data) =&gt; {
  console.log(data)
})
emitter.fire('event1', { a: 'text' })
dispose()
</code></pre><p>Consider the code above, it's intuitive that the <code>Emitter</code> class should have methods <code>on</code> and <code>fire</code> which registers an event listener and fires a specific event respectively. At a closer look, the <code>on</code> method should return a function which unregisters the event listener.
<img src="/blog/images/emitter_class.png" alt="Image of Emitter Class"></p>
<p>Recall a similar function call <code>document.addEventListener('click', () =&gt; {})</code>, one event could have multiple listeners.</p>
<p>We can start with the boilerplate for the <code>Emitter</code> class like this:</p>
<pre><code>class Emitter {
  constructor() {
    listeners = {}
  }

  on(event, fn) {}

  fire(event, data) {}
}
</code></pre><p>With the <code>on</code> method, an event listener should be registerd:</p>
<pre><code>on(event, fn) {
  this.listeners[event] = this.listeners[event] || []
  this.listeners[event].push(fn)
}
</code></pre><p>The <code>on</code> method should also return a function to unregister the listener:</p>
<pre><code>on(event, fn) {
  this.listeners[event] = this.listeners[event] || []
  this.listeners[event].push(fn)
  return function() {
    const index = this.listeners.indexOf(fn)
    this.listeners.splice(index, 1)
  }
}
</code></pre><p>The <code>emit</code> method should call each listener of the event:</p>
<pre><code>fire(event, data) {
  this.listeners[event].forEach((fn) =&gt; {
    fn.call(this, data)
  })
}
</code></pre><p>Putting together, we have <code>Emitter</code> class</p>
<pre><code>class Emitter {
  constructor() {
    listeners = {}
  }

  on(event, fn) {
    this.listeners[event] = this.listeners[event] || []
    this.listeners[event].push(fn)
    return function() {
      const index = this.listeners.indexOf(fn)
      this.listeners.splice(index, 1)
    }
  }

  fire(event, data) {
    this.listeners[event].forEach((fn) =&gt; {
      fn.call(this, data)
    })
  }
}
</code></pre><p>There are a few considerations:</p>
<ul>
<li>Passing arguments and <code>this</code> to listeners: keep in mind that when a listener function is called, <code>this</code> should be referencing <code>Emitter</code> instance</li>
<li>Asynchronous vs synchronous: <code>Emitter</code> calls all listeners synchronously in the order they were registered</li>
</ul>

      </article>
      

      

    </div>
  </div>
</div>

  </main>
  <footer class="footer">
  <div class="ax-l-i max-w-6xl">
    <nav class="flex items-center justify-center">
      <a class="ml-3 first:ml-0 text-sm text-gray-600 hover:text-gray-800" href="/blog/posts/">Posts</a>
      <a class="ml-3 first:ml-0 text-sm text-gray-600 hover:text-gray-800" href="/blog/contact/">Contact</a>
    </nav>

    <div class="footer-copyright text-sm text-center text-gray-500 mt-4">
      &#169; -2020 Mia&#39;s Blog Posts
    </div>
    <div class="text-sm sm:text-xs text-center text-gray-500 mt-2">
      Powered by <a href="https://www.axiomtheme.com/?utm_source=theme-footer&utm_medium=website&utm_campaign=referral">Axiom</a>
    </div>
  </div>
</footer>

<script src="/blog/bundle.js?v=1603792187"></script>


</body>
</html>
